from django.shortcuts import render
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.response import Response

from .models import SKU, GoodsCategory
from .serializers import SKUSerializer, SKUIndexSerializer, CategorySerializer, ChannelSerializer
# Create your views here.


# /categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
# 商品列表页， 分页和排序
class SKUListView(ListAPIView):
    # 指定查询集, 需要展示的商品， 必须是为下架的， 并且与category_id相对应， 所以要重写
    # queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定排序和分页的后端
    filter_backends = [OrderingFilter]
    # 指定排序和分页的字段， 记录时间， 价格， 销量
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id, is_launched=True)


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer



class CategoryView(GenericAPIView):
    """
    类别
    """
    queryset = GoodsCategory.objects.all()

    def get(self, request, pk=None):
        ret = dict(
            cat1='',
            cat2='',
            cat3=''
        )
        category = self.get_object()
        if category.parent is None:
            # 当前类别为一级类别
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodscategory_set.count() == 0:
            # 当前类别为三级
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前类别为二级
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(category.parent.goodschannel_set.all()[0]).data

        return Response(ret)
